package kxfang.com.user.acitvity.set;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;

import com.blankj.utilcode.util.ToastUtils;
import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.List;

import kxfang.com.base.activity.MvvmBaseActivity;
import kxfang.com.base.utils.ToastUtil;
import kxfang.com.base.viewmodel.IMvvmBaseViewModel;
import kxfang.com.common.constant.Constant;
import kxfang.com.common.dialog.MenuDialog;
import kxfang.com.common.router.RoutHub;
import kxfang.com.common.utils.DataCleanManager;
import kxfang.com.common.utils.HawkUtil;
import kxfang.com.common.utils.MyUtils;
import kxfang.com.common.utils.RouterUtils;
import kxfang.com.common.utils.StatusBarUtil;
import kxfang.com.common.views.BaseDialog;
import kxfang.com.user.BuildConfig;
import kxfang.com.user.R;
import kxfang.com.user.databinding.UserActivitySettingBinding;

import static kxfang.com.common.utils.MyUtils.getAppVersionCode;
import static kxfang.com.common.utils.MyUtils.shareDialog;

public class SettingActivity extends MvvmBaseActivity<UserActivitySettingBinding, IMvvmBaseViewModel> {
    boolean flag = false;

    //更新弹窗
    private View alertDialogView;
    AlertDialog.Builder dialog;
    AlertDialog dialog1;
//    AppDownManager appDownManager;
    private String upContent = "";
    private boolean isDownload = false;//是否点击了下载
//    private MyProgress myProgress = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        appDownManager = new AppDownManager(SettingActivity.this);
        StatusBarUtil.setTopActivityView(this, viewDataBinding.topView);
        try {
            viewDataBinding.clearData.setText(DataCleanManager.getTotalCacheSize(SettingActivity.this));
            initView();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (HawkUtil.getUserId() == null) {
            viewDataBinding.quitLogin.setVisibility(View.GONE);
            viewDataBinding.quitLine.setVisibility(View.GONE);
        }
        if (BuildConfig.DEBUG) {
            viewDataBinding.rlChangeUrl.setVisibility(View.VISIBLE);
        }
    }
    @Override
    protected IMvvmBaseViewModel getViewModel() {
        return null;
    }

    @Override
    protected int getBindingVariable() {
        return 0;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.user_activity_setting;
    }

    @Override
    protected void onRetryBtnClick() {

    }


    private void initView() {
        viewDataBinding.rlChangeUrl.setOnClickListener(view -> chooseUrlDialog());
        viewDataBinding.activityBack.setOnClickListener(v-> finish());
        viewDataBinding.appVersion.setText("当前版本" + getAppVersionCode(this));
        viewDataBinding.callPhone.setOnClickListener(v -> {
            MyUtils.callPhone(this,viewDataBinding.callPhone.getText().toString());
        });
        if (HawkUtil.getUserId() == null) {
            viewDataBinding.quitLogin.setVisibility(View.GONE);
        }
        Intent intent = new Intent();
        //关于我们
        viewDataBinding.aboutLayout.setOnClickListener(v -> {
            Bundle bundle=new Bundle();
            bundle.putString("url",Constant.LOAD_WEBVIEWURL + "/user/Aboutus?type=mobile&version=" + getAppVersionCode(this));
            bundle.putString("title","关于我们");
            RouterUtils.navigate(RoutHub.WEB_MAIN,bundle,this);
        });
        //意见反馈
        viewDataBinding.feedbackLayout.setOnClickListener(v -> {
            if (HawkUtil.getUserId() == null) {
                MyUtils.myShowDialog(this);
                return;
            }
            intent.setClass(this, FeedBackActivity.class);
            startActivity(intent);
        });
        //用户协议
        viewDataBinding.userAgreementLayout.setOnClickListener(v -> {
            intent.setClass(this, UserAgreementActivity.class);
            startActivity(intent);
        });

        viewDataBinding.clearLayout.setOnClickListener(v -> {
            try {
                DataCleanManager.clearAllCache(SettingActivity.this);
                viewDataBinding.clearData.setText(DataCleanManager.getTotalCacheSize(SettingActivity.this));
                ToastUtils.showShort("清理缓存成功");
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        viewDataBinding.selectOff.setOnClickListener(v -> {
            if (HawkUtil.getUserId() == null) {
                MyUtils.myShowDialog(this);
                return;
            }
            if (flag) {
                viewDataBinding.selectOff.setImageResource(R.drawable.setting_off);
                flag = false;
            } else {
                viewDataBinding.selectOff.setImageResource(R.drawable.setting_on);
                flag = true;
            }
        });
        //检查更新
        viewDataBinding.upAgreementLayout.setOnClickListener(v -> {
//            upApp();
        });

        //退出登录
        viewDataBinding.quitLogin.setOnClickListener(v -> {
            try {
                DataCleanManager.clearAllCache(SettingActivity.this);
                viewDataBinding.clearData.setText(DataCleanManager.getTotalCacheSize(SettingActivity.this));
            } catch (Exception e) {
                e.printStackTrace();
            }
            Hawk.delete(Constant.IM_UESR_ID);
            Hawk.delete(Constant.IM_TOKEN_SP);
            Hawk.deleteAll();
            HawkUtil.deleteAll();
//            RongIMClient.getInstance().logout();
            RouterUtils.navigate(RoutHub.PAGER_LOGIN,getBaseContext(),Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

        });
    }

//    //获取更新
//    private void upApp() {
//        TokenPar par = new TokenPar();
//        par.setTokenModel(model());
//        addSubscription(apiStores(1).upDataApp(par), new ApiCallback<UpDateModel>() {
//            @Override
//            public void onSuccess(UpDateModel model) {
//                if (model.getCode() == 200) {
//                    if (MyUtils.stringToInt(getAppVersionCode(SettingActivity.this)) < MyUtils.stringToInt(model.getData().getVersion())) {
//                        alertDialogView = getLayoutInflater().inflate(R.layout.upapp_layout, null, false);
//                        dialog = new AlertDialog.Builder(SettingActivity.this, R.style.DialogTheme);
//                        dialog.setView(alertDialogView);
//                        dialog1 = dialog.show();
//                        TextView txtVersion = alertDialogView.findViewById(R.id.appVersion);
//                        TextView txtContent = alertDialogView.findViewById(R.id.content);
//                        TextView textUp = alertDialogView.findViewById(R.id.text_up);
//                        ImageView imageView = alertDialogView.findViewById(R.id.dialog_close);
//                        myProgress = alertDialogView.findViewById(R.id.progress);
//                        for (int i = 0; i < model.getData().getCMemo().size(); i++) {
//                            upContent += model.getData().getCMemo().get(i) + "\n";
//                        }
//                        txtContent.setText(upContent);
//                        upContent = "";
//                        txtVersion.setText(model.getData().getVersion());
//                        textUp.setOnClickListener(v -> {
//                            isDownload = true;
//                            textUp.setVisibility(View.GONE);
//                            myProgress.setVisibility(View.VISIBLE);
//                            appDownManager = new AppDownManager(SettingActivity.this);
//                            appDownManager.resume();
////                            Log.e("更新", "onSuccess: " + model.getData().getDownLoadUrl());
//                            appDownManager.downloadApk(model.getData().getDownLoadUrl(), "正在下载新版本", "");
//                            appDownManager.setUpdateListener((currentByte, totalByte) -> {
//                                if (currentByte > 0 && totalByte > 0) {
////                                    Log.e(TAG, "run:" + Thread.currentThread().getName() + "：：：：" + Thread.currentThread().getId());
//                                    float pressent = (float) currentByte / totalByte * 100;//i 增加数量，mBNumber 总数
//                                    myProgress.setProgress((int) pressent);
//                                    if (pressent >= 100)
//                                        dialog1.dismiss();
//                                }
//                            });
//                        });
//                        imageView.setOnClickListener(v -> {
//                            if (model.getData().getIsForce().equals("0")) {
//                                if (!isDownload) {
//                                    dialog1.dismiss();
//                                    if (appDownManager != null)
//                                        appDownManager.cancel();
//                                } else {
//                                    toastShow("正在更新,请等待更新完成");
//                                }
//                            } else {
//                                ToastUtils.showSingleToast("当前版本需要强制更新");
//                            }
//                        });
//                    } else {
//                        toastShow("当前已是最新版本");
//                    }
//
//
//                }
//            }
//
//            @Override
//            public void onFailure(String msg) {
//
//            }
//
//            @Override
//            public void onFinish() {
//
//            }
//        });
//    }

    @Override
    protected void onResume() {
        super.onResume();
//        if (appDownManager != null) {
//            appDownManager.resume();
//        }
    }

    @Override
    protected void onPause() {
        super.onPause();
//        if (appDownManager != null) {
//            appDownManager.onPause();
//        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        if (appDownManager != null) {
//            appDownManager.cancel();
//        }

    }



    /**
     * 切换地址
     */
    private void chooseUrlDialog() {
        List<String> data = new ArrayList<>();
            data.add("线上");
            data.add("测试(外网)");
            data.add("测试(内网)");

        // 底部选择框
        new MenuDialog.Builder(this)
                // 设置 null 表示不显示取消按钮
                //.setCancel(getString(R.string.common_cancel))
                // 设置点击按钮后不关闭对话框
                //.setAutoDismiss(false)
                .setList(data)
                .setListener(new MenuDialog.OnListener<String>() {

                    @Override
                    public void onSelected(BaseDialog dialog, int position, String string) {
                        switch (position){
                            case 0:
                                Constant.init("Release");
                                break;
                            case 1:
                                Constant.init("Test");
                                break;
                            case 2:
                                Constant.init("Debug");
                                break;
                        }
                        try {
                            DataCleanManager.clearAllCache(SettingActivity.this);
                            viewDataBinding.clearData.setText(DataCleanManager.getTotalCacheSize(SettingActivity.this));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        Hawk.delete(Constant.IM_UESR_ID);
                        Hawk.delete(Constant.IM_TOKEN_SP);
                        Hawk.deleteAll();
                        HawkUtil.deleteAll();
//                        RongIMClient.getInstance().logout();

                        RouterUtils.navigate(RoutHub.PAGER_LOGIN,getBaseContext(),Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        dialog.dismiss();
                    }

                    @Override
                    public void onCancel(BaseDialog dialog) {
                    }
                }).show();

    }
}
